package impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import pojo.User;
import util.DBUtil;
import dao.UserDao;

public class UserDaoImpl implements UserDao{

	public int addUserWithDS(User u) {
		String sql="insert into users(id,uname,sal,birth,sex)values(sequ1.nextval,?,?,?,?)";
		Connection conn=null;
		PreparedStatement pst =null;
		ResultSet rs = null;
		int m = 0;
		try {
			conn=DBUtil.createConnectionWithDatasource();
			pst=conn.prepareStatement(sql);
			pst.setString(1, u.getUname());
			pst.setDouble(2, u.getSalary());
			pst.setDate(3, new java.sql.Date(u.getBirth().getTime()));
			pst.setBoolean(4, u.isSex());
			m = pst.executeUpdate();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			DBUtil.close(conn, pst, null);
		}
		System.out.println(m);
		return m;
	}

	public List<User> loadAllUsers() {
		List<User> ul = new ArrayList<User>();
		String sql="select * from users";
		PreparedStatement pst =null;
		ResultSet rs = null;
		Connection conn = null;
		User u ;
		int m =0;
		try {
			conn=DBUtil.createConnection();
			pst=conn.prepareStatement(sql);
			rs=pst.executeQuery();
			while(rs.next()){
				u=new User();
				u.setUname(rs.getString("uname"));
				u.setSalary(rs.getDouble("sal"));
				u.setBirth(new Date(rs.getDate("birth").getTime()));
				u.setSex(rs.getBoolean("sex"));
				ul.add(u);
				System.out.println(u.getUname()+"  "+u.getSalary());
			}
			m=pst.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			DBUtil.close(conn, pst, rs);
		}
		return ul;
	}

}
